import java.awt.Color;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.Selector;
import java.util.ArrayList;


public class PaintServer {




	public static ServerSocket srvSocket;
	public static int port=1234;
	public static ArrayList<SocketClient> sockets;

	public static void main(String[] args) {

		sockets=new ArrayList<SocketClient>();
		try {
			srvSocket=new ServerSocket(port);
			System.out.println("Server started..");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("Wating for client ...");

		DataOutputStream os;
		
		while(true){


			
				try {
					Socket socket=srvSocket.accept();
					Thread client=new SocketClient(socket);
					client.start();
					sockets.add((SocketClient) client);
					
					
					
					
					for(SocketClient c:sockets){
						os=new DataOutputStream(socket.getOutputStream());							
						
						for(SocketClient s:sockets){
							os.writeInt(c.player.x);
							os.writeInt(c.player.y);
						}
				
					}
					
				
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				


				


			try {
				Thread.sleep(6);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}



	}

}

class SocketClient extends Thread{
	
	Socket socket;
	Selector checker;
	BufferedInputStream is;
	Player player;
	
	public SocketClient(Socket s){
		
		this.socket=s;
		System.out.println("Client ["+socket.hashCode()+"] connected at:"+socket.getInetAddress());
		player=new Player(0, 0, Color.WHITE);
	}
	
	public void run(){
		
		
		//System.out.println("Client ["+socket.hashCode()+"] disconnected at:"+socket.getInetAddress());
		System.out.println("bound:"+socket.isBound()+", closed:"+socket.isClosed()+"connected:"+socket.isConnected());
		
		
		try {
			
			DataInputStream is=new DataInputStream(socket.getInputStream());
			int loc=0;
			while(is.readInt()!=-1){
				player.x=is.readInt();
				player.y=is.readInt();
			}
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("bound:"+socket.isBound()+", closed:"+socket.isClosed()+"connected:"+socket.isConnected());
	}
}
